package servlets;

import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.dao.MessageDAO;
import model.entity.Island;
import model.entity.Message;
import model.entity.User;
import servlets.util.ParamUtil;
import exceptions.ParameterNotFoundException;

/**
 * Servlet implementation class SendMessageServlet
 */
@WebServlet("/SendMessageServlet")
public class SendMessageServlet extends HttpServlet {

	private static final long serialVersionUID = 5608026152369051791L;

	public SendMessageServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// Parâmetros do protocolo
		List<String> paramNames = Arrays.asList("message_text",
				"message_destination", "message_author", "message_topic");
		Map<String, String> params = new HashMap<String, String>();
		try {
			params = ParamUtil.getValues(request, paramNames);
		} catch (ParameterNotFoundException e) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		Message message = new Message();
		// supõe que o id do autor corresponde a um user
		// supõe que o id do destino corresponde a uma island
		User author = new User();
		Island destination = new Island();
		try {
			author.setId(Long.parseLong(params.get("message_author")));
			destination
					.setId(Long.parseLong(params.get("message_destination")));
		} catch (NumberFormatException e) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		message.setAuthor(author);
		message.setData(Calendar.getInstance().getTime());
		message.setDestination(destination);
		message.setText(params.get("message_text"));
		message.setTopic(params.get("message_topic"));
		MessageDAO messageDAO = new MessageDAO(Message.class);
		messageDAO.create(message);
		response.setStatus(HttpServletResponse.SC_OK);
	}

}
